package com.tjs.lucky.application.mq.config;

import com.alibaba.fastjson.JSON;
import com.tjs.lucky.common.MQState;
import com.tjs.lucky.domain.activity.model.vo.DisAwardInvoiceVO;
import com.tjs.lucky.domain.activity.service.partake.IActivityPartake;
import com.tjs.lucky.infrastructure.repository.UserTakeActivityRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;

import javax.annotation.Resource;

/**
 * @author tianjiashu（mac）
 * @ClassName RabbitMQConfig.java
 * @Description 每个RabbitTemplate只能配置一个ReturnCallback
 * @createTime 2023年06月19日 23:41:00
 */
@Slf4j
@Configuration
public class RabbitMQConfig implements ApplicationContextAware {

    @Resource
    private IActivityPartake activityPartake;

    @Resource
    private UserTakeActivityRepository userTakeActivityRepository;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        // 获取RabbitTemplate
        RabbitTemplate rabbitTemplate = applicationContext.getBean(RabbitTemplate.class);
        // 设置ReturnCallback
        rabbitTemplate.setReturnCallback((message, replyCode, replyText, exchange, routingKey) -> {
            // 投递到队列端失败
            switch (routingKey) {
                case "award":
                    //发奖消息失败...
                    DisAwardInvoiceVO invoice = JSON.parseObject(new String(message.getBody()), DisAwardInvoiceVO.class);
                    activityPartake.updateInvoiceMqState(invoice.getUId(), invoice.getOrderId(), MQState.PRODUCT_FAIL.getCode());
                    break;
                default:
                    log.error("消息发送失败，应答码{}，原因{}，交换机{}，路由键{},消息{}",
                            replyCode, replyText, exchange, routingKey, message);
            }
        });
    }
}
